//线索清单表格
var $clueList = $('#clueList');

//防止表头与表格不对齐
$(window).resize(function () {
    $clueList.bootstrapTable('resetView');
});

//初始化线索池公海-线索清单
$(function () {
    if($("#defaultMark").val() == 1){
        $("#useProportion").show();
    } else {
        $("#useProportion").hide();
    }

    $('#filterContent select').selectpicker(); // 设置下拉框为bootstrap样式

    $('.custom-group input[type="checkbox"]').click('click', function () {
        let customGroup = $(this).parents('.custom-group');
        if ($(this).prop('checked')) {
            // 自定义条件筛选
            customGroup.addClass('custom-active');
            customGroup.find('select').attr('disabled', 'disabled').find('option:first').prop('selected', 'selected');
            customGroup.find('select').selectpicker('refresh');
        } else {
            // 默认条件筛选
            customGroup.removeClass('custom-active');
            customGroup.find('select').removeAttr('disabled').selectpicker('refresh');
            $(this).parents('.custom-box').find('input[type="text"]').val('');
        }
    });

    clueListInit();
});

function clueListInit() {
    //先销毁表格
    $clueList.bootstrapTable('destroy');
    $clueList.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: '/clue/getMyClueList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",// 请求内容类型
        // contentType: "application/json",// 请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'ownerStartTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,                                // 是否启用点击选中行
        maintainSelected: true,                             // 分页是否保留选中
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'clueId',
        idField: 'clueId',
        serverSelected: true,// 开启后端分页记住已选项功能
        serverSelectedField: 'clueId',// 已选项的唯一识别主键
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数
        queryParams: queryParamsMin,//查询参数
        columns: [
            {field : 'checked', checkbox: true, align: 'center', valign: 'middle'},
            {title: '主键', field: 'clueId', visible: false},
            // {title: '全选', field: 'checked', align: 'left', checkbox: true, valign: 'middle',width: '60'},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '60', formatter: indexFormat},
            {title: '客户名称', field: 'companyName', align: 'left', valign: 'middle'},
            {title: '联系人', field: 'contactPerson', align: 'left', valign: 'middle'},
            // {title: '电话', field: 'contactPersonPhone', align: 'left', valign: 'middle',formatter:phoneNumber},
            {title: '职务', field: 'job', align: 'left', valign: 'middle'},
            {title: '线索来源', field: 'source', sortable: true,align: 'left', valign: 'middle'},
            {title: '线索标签', field: 'tag', align: 'left', valign: 'middle', width: '14%', formatter: formatTag},
            // {title: '线索评级', field: 'rating',align: 'left', valign: 'middle'},
            {title: '领取时间', field: 'ownerStartTm', sortable: true, align: 'left', valign: 'middle'},
            {title: '操作', field: 'operate',align: 'right', events: operateEvents, formatter: genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //是否是默认池子：0-不是默认；1-默认池子
            var defaultMark = $("#defaultMark").val();
            if(defaultMark == '1'){
                $('#buttonGroupMain').css('display', 'none');
                $('#clueCapacity').css('display', 'block');
                $('.progress-bar').width($('.clue-info .clue-num').html() / $('.clue-info #capacity').html() * $('.progress').width())
            } else {
                $clueList.bootstrapTable('hideColumn', 'ownerStartTm'); // 不是默认线索池，隐藏领取时间列
                $('#buttonGroupMain').css('display', 'block');
                $('#clueCapacity').css('display', 'none');
            }
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方

            // table操作列下拉菜单效果
            tableNav();
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

/*搜索点击事件*/
function searchClueList(value){
    if (value == 1) {
        $clueList.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParamsMin});
    } else {
        $clueList.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
    }
}

/* 重置查询条件 */
function reset() {
    $('#filterContent select').val('').selectpicker('refresh');
    $('#filterContent input').val('');
    // 默认条件筛选
    $('.custom-group').removeClass('custom-active');
    $('.custom-group').find('select').removeAttr('disabled').selectpicker('refresh');
    $('.custom-group').find('input[type="checkbox"]').removeAttr('checked');
    $('.custom-box').find('input[type="text"]').val('');
    searchClueList() // 高级搜索 查询
}

/* 列表序列号*/
function indexFormat(value, row, index) {
    return index + 1;
}


 /*拼接线索池表格查询条件参数*/
function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    //普通搜索条件
    params.poolId = $('#poolId').val();
    params.companyName = $.trim($('#companyName').val());//公司名称
    params.clueNumber = $.trim($('#clueNumber').val());//线索ID
    params.source = $.trim($("#source").val());//线索来源

    var industryType = $('#industryType').val();//行业
    var enterpriseType = $('#enterpriseType').val();//公司类型
    var approvalDate;//成立年限
    if($('#approvalDate').attr('disabled')){
        approvalDate = $('#beginYearsEstablishment').val()+'-'+$('#endYearsEstablishment').val()+'年'
    }else{
        approvalDate = $('#approvalDate option:selected').text() == '请选择' ? '' : $('#approvalDate option:selected').text();
    }
    var insuredTotal ;//参保人数
    if($('#insuredTotal').attr('disabled')){
        insuredTotal = $('#beginInsuredNumbers').val()+'-'+$('#endInsuredNumbers').val()+'人'
    }else{
        insuredTotal = $('#insuredTotal option:selected').text() == '请选择' ? '' : $('#insuredTotal option:selected').text();
    }
    var registCapital;//注册资本
    if($('#registCapital').attr('disabled')){
        registCapital = $('#beginRegisteredCapital').val()+'-'+$('#endRegisteredCapital').val()+'万'
    }else{
        registCapital = $('#registCapital option:selected').text() == '请选择' ? '' : $('#registCapital option:selected').text();
    }
    var isExistContactPersonPhone = $('#isExistContactPersonPhone').val();//是否有联系电话
    var isExistContactPerson = $('#isExistContactPerson').val();//是否有联系人
    var isExistCompanyEmail = $('#isExistCompanyEmail').val();//是否有邮箱
    var tags = $('#tags').val();//标签
    var provinceName = $('#provinceName').val();//省
    var cityName = $('#cityName').val();//市
    var countyName = $('#countyName').val();//县
    var registStatus = $('#registStatus').val();//目前状态
    var customerType = $('#customerType').val();//客户类型

    params.industryType = industryType;                     // 所属行业
    params.enterpriseType = enterpriseType;                 // 公司类型
    params.approvalDate = approvalDate;                     // 成立年限
    params.registCapital = registCapital;                   // 注册资本
    params.insuredTotal = insuredTotal;                     // 参保人数
    params.hasPerson = isExistContactPerson;                 // 是否有联系人
    params.hasPhone = isExistContactPersonPhone;                 // 是否有联系人电话
    params.hasEmail = isExistCompanyEmail;                  // 是否有联系邮箱
    params.sysTag = tags;                                   // 标签
    params.provice = provinceName;                          // 省份(模糊查询)
    params.city = cityName;                                 // 城市(模糊查询)
    params.district = countyName;                           // 区县(模糊查询)
    params.registStatus = registStatus;                     // 目前状态
    params.customerType = customerType;                     // 客户类型
    return params;
}
function queryParamsMin(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    //普通搜索条件
    params.poolId = $('#poolId').val();
    params.companyName = $.trim($('#companyNameMin').val());//公司名称
    return params;
}

function phoneNumber(value,row,index){
    if(value == ''){
        return [
            `<span title="电话为空" data-toggle="tooltip">---</span>`
        ];
    }else{
        var tel = value;
        tel = "" + tel;
        var reg=/(\d{3})\d{4}(\d{4})/;
        var tel1 = tel.replace(reg, "$1****$2");
        return [
            `<span><i class="mdi mdi-phone"></i>${tel1}</span>`
        ];
    }

}

function formatTag(value) {
    let html = '';
    if (value !== null) {
        let tagsArr = value.split(',');
        for (let i = 0; i < tagsArr.length; i++) {
            html += '<span class="label label-outline-warning">' + tagsArr[i] + '</span>';
        }
    }
    return html;
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    return [
        '<button type="button" id="detail" class="btn btn-default"><i class="mdi mdi-eye"></i>详情</button>',
        '<div class="dropdown">',
        '<button type="button" id="followUp" class="btn btn-default" data-index="' + index + '"><i class="mdi mdi-image-filter-tilt-shift"></i>跟进</button>' +
        '<ul class="dropdown-menu">',
        '<li><a href="JavaScript:void(0);" onclick="callCenter(\'' + row.clueId + '\');">线上电话</a></li>',
        '<li><a href="JavaScript:void(0);" onclick="goOnline(\'offline\', \''+row.clueId+'\')">线下电话</a></li>',
        '<li><a href="JavaScript:void(0);" onclick="goOnline(\'visit\', \''+row.clueId+'\')">拜访</a></li>',
        '<li><a href="JavaScript:void(0);" onclick="goOnline(\'WeChat\', \''+row.clueId+'\')">微信交流</a></li>',
        '<li><a href="JavaScript:void(0);" onclick="goOnline(\'accompanyingVisit\', \''+row.clueId+'\')">陪访</a></li>',
        '<li><a href="JavaScript:void(0);" onclick="goOnline(\'email\', \''+row.clueId+'\')">电子邮件</a></li>' +
        '</ul>' +
        '</div>',
        '<button type="button" id="conversion" class="btn btn-default" onclick=\'convertToCustomer("'+row.clueId+'")\'><i class="mdi mdi-rotate-right"></i>转化</button>',
        '<button type="button" id="release" class="btn btn-default"><i class="mdi mdi-reply"></i>释放</button>',
    ].join('');
}

/**
 * 功能: 呼出拨号窗口
 * 参数: customerId-客户id contactData-联系人相关数据([{}]数组形式传递)
 * */
function callCenter(clueId) {
    $.ajax({
        url: '/clue/userClueRecord',
        type: 'post',
        dataType: "json",
        contentType: "application/x-www-form-urlencoded",
        data: {
            pageSize: '',
            pageIndex: '',
            clueId,
            tabType: '4',
        },
        success: function (data) {
            if (data.code == '000000') {
                var clueData = data.data;
                var callData = [];
                for (let i = 0; i < clueData.length; i++) {
                    var contactInfo = {
                        contactId: clueData[i].clueContactId,
                        contactName: clueData[i].contactName,
                        contactDetails: [clueData[i].contactInformation],
                    }
                    callData.push(contactInfo);
                }
                window.parent.callModal("", callData, 0, clueId);
            } else {
                promptInfo('错误代码：' + data.code);
            }
        },
        error: function (res) {
            promptInfo('数据请求失败，请重试！(' + res + ')');
        }
    })
}

/**
 * 自定义操作列事件
 */
window.operateEvents = {
    // 跟进
    'click #followUp': function (e, value, row, index) {
        // followUpFun(row);
    },
    //释放
    'click #release': function (e, value, row, index) {
        releaseClue(row.clueId);
    },
    //详情
    'click #detail': function (e, value, row, index) {
        parent.$(parent.document).data('multitabs').create({
            iframe : true,
            title : '线索详情',
            url : "/front/cluePoolManager/user/clueDetail?clueId=" + row.clueId
        }, true);
    }

};
// 跳转线上线下电话跟进   跟进方式：1-线上电话；2-拜访 3-微信 4-线下电话 5-邮箱 6-陪访
function goOnline(name, id) {
    var poolId = $('#poolId').val();
    var clueId = id;
    var type = '';
    var title = '跟进';
    var source = '0';//从哪跳转到跟进页面（0：线索；1：客户）
    // 线上电话
    if (name == 'online') {
        type = "1";
        title = '线索跟进-线上电话';
    }
    // 拜访
    if (name == 'visit') {
        type = "2";
        title = '线索跟进-拜访';
    }
    // 微信
    if (name == 'WeChat') {
        type = "3";
        title = '线索跟进-微信交流';
    }
    // 线下电话
    if (name == 'offline') {
        type = "4";
        title = '线索跟进-线下电话';
    }
    // 电子邮件
    if (name == 'email') {
        type="5";
        title = '线索跟进-电子邮件';
    }
    // 陪访
    if (name == 'accompanyingVisit') {
        type = "6";
        title = '线索跟进-陪访';
    }
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : title,
        url : "/front/contactManager/user/clueFollow?type="+ type +"&id=" + clueId
            +"&poolId=" +poolId +"&source=" +source
    }, true);
}

function releaseClue(clueId) {
    $("#clueId").val(clueId);
    $('#retrieveClueModal').modal('show');
}


/**
 * 我的线索池-线索清单释放
 * @param clueId     ---线索主键
 */
function confirmReturnClue () {
    var returnReason = $('#returnReason').val();//线索释放原因
    if(!returnReason){
        $.alert("释放原因不能为空");
        return;
    }else {
        if (returnReason.length > 100) {
            $.alert("释放原因不能大于100个字！");
            return;
        }
    }
    var poolId = $("#poolId").val();
    var clueId = $("#clueId").val();
    //是否是默认池子：0-不是默认；1-默认池子
    var defaultMark = $("#defaultMark").val();
    $.alert({
        title: '提示',
        content: "确定要释放吗？",
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/clue/releaseClue",
                        data: {
                            clueId: clueId,
                            cluePoolFromId: poolId,
                            returnReason:returnReason,
                            defaultMark:defaultMark
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.code == '000000') {
                                $.alert('释放成功!');
                                $clueList.bootstrapTable('refreshOptions', {pageNumber: 1});
                            } else {
                                $.alert(data.message);
                            }
                        },
                        error: function () {
                            $.alert('释放失败，请稍后再试!');
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                }
            }
        }
    });

    $('#retrieveClueModal').modal('hide');
}


/**
 * 关闭线索释放模态框
 */
function cancelReturnClue() {
    $('#retrieveClueModal').modal('hide');
}

// 新增线索
function goAddClue() {
    var poolId = $("#poolId").val();
    var defaultMark = $("#defaultMark").val();
    var capacity = $("#capacity").val();
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '新增线索',
        url: "/front/user/addClue?poolId=" + poolId +"&defaultMark="+defaultMark + "&capacity=" + capacity
    }, true);
}

//批量删除操作
function deleteDataOperate(){
    var selectDatas = $clueList.bootstrapTable("getSelections");
    if(selectDatas.length > 0){
        $.confirm({
            title: '提示',
            content: '是否确认删除',
            buttons: {
                confirm: {
                    text: '确认',
                    btnClass: 'btn-primary',
                    action:function(){
                        deleteData(getDataArr(selectDatas,'clueId'))
                    }
                },
                cancel: {
                    text: '取消',
                    btnClass: 'btn-primary',
                    action: function () {
                        return;
                    }
                }
            }
        });
    }else{
        $.alert({
            'title':'提示',
            'content':'请选择要删除的数据'
        })
    }
}

//数组转字符串
function getDataArr(data, fileName){
    let arr=[];
    data.filter((item)=>{
        arr.push(item[fileName])
    })
    return arr
}

//删除
function deleteData(idsArr){
    $.ajax({
        type: "post",
        url: '/clue/batchDeleteClueByClueIds',
        traditional: true,
        data: {"ids": idsArr},
        dataType: 'json',
        success: function (data) {
            if (data.code == '000000') {
                $.alert({
                    title:'提示',
                    content:'删除成功!',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                if ($('#filterContent').attr('aria-expanded') == 'true') {
                                    searchClueList(); // 高级搜索
                                } else {
                                    searchClueList(1);
                                }
                            }
                        }
                    }
                });
            } else {
                $.alert({
                    title: '提示',
                    content: data.message
                });
            }
        },
        error: function () {
            $.alert({
                title: '提示',
                content: '删除失败，请稍后再试!'
            });
        }
    });
}

//显示导入线索模态框
function showImportClueModal(){
    $('#importClueModal').modal('show');
}

//取消导入线索模态框
function cancelImportClueList() {
    $("#importClueFile").val("");
}


//导入入职名单
/*function importClueList() {
    //线索池主键
    var poolId = $("#poolId").val();
    if(!document.getElementById('importClueFile').files[0]){
        $.alert({
            title: '温馨提示',
            content: '请选择文件！',
        });
        return;
    }
    var fileName = document.getElementById('importClueFile').files[0].name;
    var fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length);
    var formData = new FormData();
    //接口接收参数 键值形式 添加到formData中
    formData.append("file",$("#importClueFile")[0].files[0]);
    formData.append("clueType",2);
    formData.append("clueStatus",1);
    formData.append("poolId",poolId);
    if(fileName!="" && (fileType.toLocaleUpperCase()==".XLSX"||fileType.toLocaleUpperCase()==".XLS")){
        $.ajax({
            url: '/clueImport/clueImport',
            type: 'POST',
            dataType:"json",
            contentType:false,
            data: formData,
            processData: false,
            success:(function(data) {
                if(data.code == "000000"){
                    //线索导入数量
                    var importClueNum = data.data.importClueNum;
                    var repeatIdStr = data.data.repeatIdStr;
                    var importFailIdStr = data.data.importFailIdStr;

                    //返回内容
                    var content = "";

                    //导入数量大于0
                    if(importClueNum>0){
                        content = "成功导入"+importClueNum+"条数据";
                    }
                    //重复id不为空
                    if(typeof(repeatIdStr) != "undefined"&&repeatIdStr!=""){
                        content = content + "<br>excel表格第：" + repeatIdStr + "行线索已存在";
                    }
                    //失败id不为空
                    if(typeof(importFailIdStr) != "undefined"&&importFailIdStr!=""){
                        content = content + "<br>excel表格第：" + importFailIdStr + "行线索导入失败";
                    }

                    $.alert({
                        title: '提示',
                        content: content,
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    $("#importClueFile").val("");
                                    $clueList.bootstrapTable('refresh');
                                }
                            }
                        }
                    });
                    $('#importClueModal').modal('hide');
                    $("#importClueFile").val("");
                }else if(data.code == "CI0001"){
                    $.alert({
                        title: '提示',
                        content: data.message,
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    $("#importClueFile").val("");
                                }
                            }
                        }
                    });
                }else{
                    $.alert("导入失败");
                    $("#importClueFile").val("");
                }
            }),
            error:(function() {
                $.alert("导入出错！");
                $("#importClueFile").val("");
            })
        });
    } else {
        $.alert({
            title: '温馨提示',
            content: '请上传.xlsx或.xls文件！',
        });
    }
}*/

/**
 * 下载模板
 */
function downClueTemplate(){
    var url="/clueImport/downloadClueTemplate";
    window.location.href=encodeURI(encodeURI(url));
}

//转化为客户
function convertToCustomer(clueId) {
    $.ajax({
        url: '/customerController/convertToCustomer',
        type: 'POST',
        dataType: "json",
        data: {
            clueId : clueId
        },
        success: (function (data) {
            if (data.code == "000000") {
                clueListInit();
                $.alert("转化成功！");
            } else if (data.code == "CF0001") {
                $.alert("这个线索已经转化过客户了!!!");
            } else if (data.code == "CF0002") {
                $.alert("您已经有175个非会员客户了,不能转化客户!!!");
            } else if (data.code == "CF0004") {
                $.alert("客户名称已关联客户,不能转化客户!!!");
            } else if (data.code == "C00030") {
                $.alert("企业客户信息错误,请核实!!!");
            } else {
                alert("保存失败");
            }
        }),
        error: (function () {
            alert("失败");
        })
    });
}

/**
 * 功能：提示信息
 */
function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                scrollToPreviousElement: false,
                scrollToPreviousElementAnimate: false,
            }
        }
    });
}